import axios from 'axios';
import qs from 'qs';
import { storage } from '@/utils';
import { showLoading, closeLoading } from '@/utils/loading';
const timeout = 50000;
import { AxiosInstance } from 'axios';
import { ApiResponse } from '@/interface/api/public';
import { getBaseUrl } from '@/utils/index';
//给AxiosRequestConfig扩展字段
declare module 'axios' {
  interface AxiosRequestConfig {
    loading?: boolean,
  }
  interface AxiosResponse {
    loading?: boolean
  }
}

//实例化axios
const service: AxiosInstance = axios.create({
  // baseURL: import.meta.env.VITE_BASE_URL as string, // api 的 base_url
  baseURL: getBaseUrl(),
  withCredentials: true, // 跨域请求时发送 cookies
  timeout: timeout, // request timeout  30s
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
    language: import.meta.env.VITE_DEFAULT_LANGUAGE
  },
  loading: true,
});

// 表示跨域请求时是否需要使用凭证
service.defaults.withCredentials = false;

// 请求拦截器
service.interceptors.request.use(
  config => {
    //请求方式
    const method: string = config.method.toLocaleLowerCase();

    //处理get请求
    if (method === 'get') {
      config.params = config.data;
      //对get请求数据进行qs序列化处理
      config.paramsSerializer = function () {
        //去除为空和undefind的字段
        for (const key in config.params) {
          config.params[key] ?? delete config.params[key];
        }
        return qs.stringify(config.params, { arrayFormat: 'indices' });
      };
    }

    //国际化语言设置
    const language = storage.getLocal('language');
    language && (config.headers['language'] = language);

    //接口需要loading 则开启loading
    config.loading && showLoading();

    return config;
  },
  error => {
    return Promise.reject(error.data.error.message);
  });

// 响应拦截器
service.interceptors.response.use(
  response => {
    //关闭loading
    response.config.loading && closeLoading();
    const { code } = response.data;
    switch (code) {//根据实际项目需求增加code
      case 401:
        //401
        break;
      default:
        return Promise.resolve(response.data);
    }
  },
  error => {
    // closeLoading();
    if (error?.config.loading !== false) {
      closeLoading();
    }

    if (error.response.status) {
      return Promise.reject(error.response);
    }
  }
);
export default service;